package com.kaifamiao.comparator;

import java.util.Arrays;
import java.util.Comparator;

public class MonkeyTest2 {

	public static void main(String[] args) {
		
		Monkey[] monkeys = new Monkey[5];
		
		monkeys[ 0 ] = new Monkey( "弼马温" , '男' , 25000 , 120 );
		monkeys[ 1 ] = new Monkey( "美猴王" , '女' , 30000 , 140 );
		monkeys[ 2 ] = new Monkey( "孙悟空" , '男' , 24000 , 110 );
		monkeys[ 3 ] = new Monkey( "孙行者" , '女' , 32000 , 130 );
		monkeys[ 4 ] = new Monkey( "行者孙" , '男' , 20000 , 108 );
		
		System.out.println( Arrays.toString( monkeys ) );
		
		Arrays.sort( monkeys );
		
		System.out.println( Arrays.toString( monkeys ) );
		
		// 用 匿名类 实现 java.util.Comparator 接口并实现 compare 方法
		Comparator<Monkey> comparator = new Comparator<Monkey>() {
			@Override
			public int compare(Monkey one, Monkey another) {
				if( one.height < another.height ) {
					return -1 ;
				} else if( one.height == another.height ) {
					return 0 ;
				} else {
					return 1 ;
				}
			}
		} ;
		
		// 按照身高进行排序
		for( int i = 0 , m = monkeys.length - 1 ; i < m ; i++ ) {
			for( int j = 0 , n = m - i ; j < n ; j++ ) {
				// 若相邻的两个元素中前一个比后一个大
				if( comparator.compare( monkeys[ j ] , monkeys[ j + 1 ]) > 0 ) {
					Monkey p = monkeys[ j ] ;
					monkeys[ j ] = monkeys[ j + 1 ] ;
					monkeys[ j + 1 ] = p ;
				}
			}
		}
		
		System.out.println( Arrays.toString( monkeys ) );
		

	}

}
